package com.gitee.huanminabc.utils_tools.security.access;

import com.gitee.huanminabc.utils_tools.security.enums.AuthEnum;
import com.gitee.huanminabc.utils_tools.security.vo.SecurityResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义未登录时：返回状态码401
 * 认证失败
 */
@Component
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Object attribute = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        if (Objects.isNull(attribute)){
            //没有登陆的时候会走这里
            SecurityResponse.error(401, "未登录,请先登录!",response);
            return;
        }
        Throwable  t = (Throwable) attribute;
        String message = t.getMessage();
        //判断是否有-   , 登陆异常的情况
        if(AuthEnum.isShow(message)){
            String[] split = message.split("-");
            SecurityResponse.error(AuthEnum.valueOf(split[0]).getCode(), split[1],response);
        }else{
            // 未知错误,因为没有登录所以不给具体的错误信息
            SecurityResponse.error(401, "未登录,请先登录!",response);
        }
    }

}
